package org.zattix.ejb;

import java.nio.channels.NonReadableChannelException;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.*;
import org.zattix.bean.Category;
import org.zattix.util.Logger;

/**
 *
 * @author s.rainoldi
 */
@Stateless
public class CategoryFacade extends AbstractFacade<Category> {

    @PersistenceContext
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public CategoryFacade() {
        super(Category.class);
    }

    public Category getCategoryByTitleUrl(String titleUrl) {
        Category category;
        try {
            category = (Category) ((Query) getEntityManager().createQuery("select c from Category c where c.titleUrl = :titleUrl")).setParameter("titleUrl", titleUrl).getSingleResult();
            Logger.log("User found");
        } catch (NoResultException e) {
            Logger.log("No category found. Url: " + titleUrl + "", Logger.WARNING);
            return null;
        } catch (NonUniqueResultException e) {
            Logger.log("More than one category found with the following url: " + titleUrl + "", Logger.WARNING);
            return null;
        }
        return category;
    }
    /*
     * Returns all but by alphabetical order
     */

    @Override
    public List<Category> findAll() {
        List<Category> categories = getEntityManager().createQuery("select c from Category c order by c.title asc").getResultList();
        return categories;
    }
}
